package config_init

import (
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
	"go_server/center_server/util"
	"go_server/zinx/zlog"
	"go_server/zinx/zutils"
)

var serverConfigViper *viper.Viper

func init() {
	configViper, fullPathFile := util.CreateConfig("center_server")
	configViper.WatchConfig()
	configMD5 := zutils.ReadFileMd5(fullPathFile)

	logDir := configViper.GetString("log_dir")
	logFile := configViper.GetString("log_file")
	if len(logFile) > 0 {
		zlog.SetLogFile(logDir, logFile)
	}
	logCons := configViper.GetBool("log_cons")
	if logCons {
		zlog.SetCons(logCons)
	}
	logSaveDays := configViper.GetInt("log_save_days")
	if logSaveDays > 0 {
		zlog.SetMaxAge(logSaveDays)
	}
	logLevel := configViper.GetInt("log_level")
	if logLevel >= 0 {
		zlog.SetLogLevel(logLevel)
	}
	configViper.OnConfigChange(func(in fsnotify.Event) {
		changeMD5 := zutils.ReadFileMd5(fullPathFile)
		if changeMD5 == configMD5 {
			return
		}
		configMD5 = changeMD5
		logDir = configViper.GetString("log_dir")
		logFile = configViper.GetString("log_file")
		if len(logFile) > 0 {
			zlog.SetLogFile(logDir, logFile)
		}
		logCons = configViper.GetBool("log_cons")
		if logCons {
			zlog.SetCons(logCons)
		}
		logSaveDays = configViper.GetInt("log_save_days")
		if logSaveDays > 0 {
			zlog.SetMaxAge(logSaveDays)
		}
		logLevel = configViper.GetInt("log_level")
		if logLevel >= 0 {
			zlog.SetLogLevel(logLevel)
		}
	})

	serverConfigViper = configViper
}

func GetConfigViper() *viper.Viper {
	return serverConfigViper
}
